package com.yudean.esb.security.impl;

import com.yudean.esb.domain.sys.AppUser;
import com.yudean.esb.mapper.sys.SysAppUserMapper;
import com.yudean.esb.security.SysAppUserService;
import com.yudean.esb.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class SysAppUserServiceImpl implements  SysAppUserService{

    @Resource
    private SysAppUserMapper sysAppUserMapper;
    private String errMsg = null;

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    @Override
    public String getErrMsg() {
        return errMsg;
    }

    @Override
    public boolean hasPermit(String compCode, String userCode, String password) {
        final String enPassword = StringUtil.encodePassword(password, "SHA");
        List<AppUser> lists = sysAppUserMapper.hasPermit(compCode,userCode,enPassword);
        if(lists != null && !lists.isEmpty()){
            return true;
        }
        this.setErrMsg(getErrMessage(userCode + ":用户名或密码错误，或者无权限访问该公司数据:"
                + compCode + ";" + password + ";" + enPassword));
        return false;
    }

    @Override
    public boolean hasPermit(String userCode, String password) {
        final String enPassword = StringUtil.encodePassword(password, "SHA");
        List<AppUser> lists = sysAppUserMapper.hasPermit(null,userCode,enPassword);
        if(lists != null && !lists.isEmpty()){
            return true;
        }
        this.setErrMsg(getErrMessage(userCode + ":用户名或密码错误:" + password + ";" + enPassword));
        return false;
    }


    public String getErrMessage(String errMsg) {
        StringBuffer xmlSb = new StringBuffer();

        xmlSb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        xmlSb.append("<service>\n");
        xmlSb.append("<ResultMessage>" + errMsg
                + "</ResultMessage><!--处理的失败消息 -->\n");
        xmlSb.append("<ResultCode>0</ResultCode><!--0表示失败-->\n");
        xmlSb.append("</service>\n");
        return xmlSb.toString();
    }


}
